# default configure
from Shell.configure.ConfigureAccess import ConfigureGet,ConfigureSave
# test: command pipe
from Cube.command import CommandPipeReset, CommandPipeGet
# test: map loader
from Cube.map import MapMgrGet, SingleMapHeadLoad
import sys, os
# QMemberType
from Cube.map import QMemberType

class LoginModel:
    def __init__(self):
        # get current login configure
        self.LoginInfo = ConfigureGet("Login")
        self.Nickname = self.LoginInfo["Nickname"]
        self.ConnectType = [self.LoginInfo["ConnectType"]]  #["server"] or ["client"]
        self.HostIP = self.LoginInfo["HostIP"]

    def IPSet(self, ipAddress):
        self.HostIP = ipAddress
        if self.ConnectType[0] == "client":
            if ipAddress:
                bSuccess = True
            else:
                bSuccess = False
        else:
            bSuccess = True
        return bSuccess

    def LoginInfoSave(self):
        self.LoginInfo["Nickname"] = self.Nickname
        self.LoginInfo["ConnectType"] = self.ConnectType[0]
        self.LoginInfo["HostIP"] = self.HostIP
        ConfigureSave({"Login":self.LoginInfo})

    def GameLobbyCreateHandle(self):
        self.LoginInfoSave()
        if (self.ConnectType[0] == 'server'):
            # map loader - server only
            # ----
            # add path into sys.path
            mapPath = "%s\\Shell\\ghost\\SampleMap"%(os.getcwd())
            sys.path.append(mapPath)
            from SampleMap import SampleMap
            # ----
            mapHeaderKlass = SampleMap # test
            SingleMapHeadLoad(SampleMap)
            mapMgr = MapMgrGet()
            cmdPipeType = "server"
            memberList = mapMgr.CurrentMapHeader.MemberListGet()
            HumanTypeCnt = HumanTypeCntGet(memberList)
            networkSetupParam = dict( acceptedConnectionNum = (HumanTypeCnt-1) )
            CmdDispatchPeriods = mapMgr.CmdSyncPeriodGet()
        else:
            # IMPORTANT: map loading of client is at GameLobbyClient
            cmdPipeType = "client"
            networkSetupParam = dict( ip_address = self.HostIP )
            CmdDispatchPeriods = 0.1
        cmdPipe = CommandPipeReset(cmdPipeType, CmdDispatchPeriods= CmdDispatchPeriods )
        bSuccess = cmdPipe.NetworkSetup(**networkSetupParam)
        return bSuccess


def HumanTypeCntGet(memberList):
    ret = sum([(QMemberType.HUMAN in entry.OptionMemberType) \
                for entry in memberList])
    return ret
